package top.i51213.fastaction.view;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import top.i51213.fastaction.R;
import top.i51213.fastaction.uri.UriReader;
import top.i51213.fastaction.util.IOUtil;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.Toast;

import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class OfficeReaderActivity extends AppCompatActivity implements TbsReaderView.ReaderCallback {
    private ReaderView tbsReaderView;
    private File docFile;
    private String ext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_office_reader);
        initReader();
        String type = getIntent().getType();
        if(type==null)return;
        checkExt(type);
        Uri uri=getIntent().getData();
        boolean success= checkFile(uri);
        if(success){
            if(!openDocxWithLocal()){
                openDocx2();
            }
            return;
        }
        Toast.makeText(this,"无法打开文件",Toast.LENGTH_SHORT).show();
    }

    private void initReader() {
        ViewGroup rl = findViewById(R.id.office_reader_layout);
        tbsReaderView = new ReaderView(this, this);
        tbsReaderView.setBackgroundColor(Color.GRAY);
        rl.addView(tbsReaderView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }
    private void checkExt(String type){
        switch (type){
            case "application/msword":
                ext="doc";break;
            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                ext="docx";break;
            case "application/vnd.ms-excel":
                ext="xls";break;
            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                ext="xlsx";break;
            case "application/vnd.ms-powerpoint":
                ext="ppt";break;
            case "application/vnd.openxmlformats-officedocument.presentationml.presentation" :
                ext="pptx";break;
            case "text/plain" :
                ext="txt";break;
            default: ext="unknown";break;
        }
    }
    private boolean checkFile(Uri uri){
        UriReader uriReader=new UriReader(this,uri);
        if(uriReader.getFile()!=null){
            docFile=uriReader.getFile();
        }else {
            String disPlayName = null;
            if (uriReader.getDisPlayName() != null) {
                disPlayName = uriReader.getDisPlayName();
                if (!disPlayName.contains(".")) {
                    disPlayName += "." + ext;
                }
            }
            if(disPlayName==null){
                disPlayName= IOUtil.getRandomTime()+"."+ext;
            }
            docFile = IOUtil.createCacheFile(this, disPlayName);
            try {
                InputStream in = uriReader.openInputStream();
                OutputStream out = new FileOutputStream(docFile);
                IOUtil.copyToAndClose(in, out);
            } catch (Exception ignored) {
            }
        }
        return docFile!=null&&docFile.exists();
    }

    private boolean openDocxWithLocal() {
        boolean canOpen = tbsReaderView.preOpen(ext, false);
        System.out.println("openDocxWithLocal:" + canOpen);
        if (canOpen) {
            Bundle bundle = new Bundle();
            bundle.putString("filePath", docFile.getPath());
            bundle.putString("tempPath", getExternalCacheDir().getPath());
            tbsReaderView.openFile(bundle);
        }
        return canOpen;
    }

    private void openDocx2() {
        HashMap<String, String> extraParams = new HashMap<>();
        extraParams.put("local", "false");
        QbSdk.openFileReader(this, docFile.getPath(), extraParams, s -> {
            System.out.println("open file with reader for " + docFile.getPath() + " result:" + s);
        });
    }

    @Override
    public void onCallBackAction(Integer actionId, Object o, Object o1) {
        //System.out.println("onCallBackAction-> actionId:"+actionId+" obj1:"+o+" obj2:"+o1);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_office_reader, menu);
        return true;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_reader_full:
                openDocx2();
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        tbsReaderView.onStop();
    }

    private void sendHover(final float x, final float y, int step, final boolean down) {
        int k = down ? 1 : -1;
        long downTime = SystemClock.uptimeMillis();
        long eventTime = downTime;
        List<MotionEvent> motionEvents = new ArrayList<>();
        MotionEvent downEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, x, y, 0);
        motionEvents.add(downEvent);
        tbsReaderView.dispatchTouchEvent(downEvent);

        for (int i = 0; i < step; i++) {
            MotionEvent moveEvent = MotionEvent.obtain(downTime, eventTime += 60, MotionEvent.ACTION_MOVE, x, y + (30 * k * i), 0);
            motionEvents.add(moveEvent);
            tbsReaderView.dispatchTouchEvent(moveEvent);
        }
        MotionEvent upEvent = MotionEvent.obtain(downTime, eventTime + 60, MotionEvent.ACTION_UP, x, y + (30 * k * (step - 1)), 0);
        motionEvents.add(upEvent);
        tbsReaderView.dispatchTouchEvent(upEvent);
        for (MotionEvent e : motionEvents) {
            e.recycle();
        }
    }
}